package com.atguigu.lease.web.app.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.web.app.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    Client client;


    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void sendCode(String phone, String verifyCode) {
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phone);
        smsRequest.setSignName("阿里云短信测试");
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\"" + verifyCode + "\"}");
        try {
            client.sendSms(smsRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void getSMSCode(String phone) {
        //非空判断
        if(!StringUtils.hasText(phone)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }


        String phoneNum = RedisConstant.APP_LOGIN_PREFIX+phone;
        //检查手机号是否存在
        if (redisTemplate.hasKey(phoneNum)){
            //若已存在 则判断验证码在reids的存在时间是否小于1分钟 弱国否 则抛出异常 手机号验证码发送频率过高
            Long expire = redisTemplate.getExpire(phoneNum);
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC-expire<RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        //生成验证码发送 并存到redis
        String verifyCode = VerifyCodeUtil.getVerifyCode(6);
        sendCode(phone,verifyCode);

        //存到redis

        redisTemplate.opsForValue().set(phoneNum,verifyCode,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);

    }
}
